<template>
	<view>
		<view class="top" :style="isvip==1?'background-image: linear-gradient(0.5turn, #ffffff, #4F46E5);':''">
			<view style="display: flex;justify-content: space-between;"><span>当前会员状态</span><span>加油包剩余沟通次数</span></view>
			<view style="display: flex;justify-content: space-between;">
				<p v-if="isvip == 1" :style="isvip==1?'color:white;font-weight:bold;':''">VIP<span
						:style="isvip==1?'color:white':''" v-if="perOrEnt == 'per'">(个人)</span><span
						:style="isvip==1?'color:white':''" v-if="perOrEnt == 'ent'">(企业)</span> </p>
				<p v-else>普通用户</p>
				<p :style="isvip==1?'color:white;font-weight:bold;':''">{{quantity}}次</p>
			</view>
			<span v-if="isvip == 1" :style="isvip==1?'color:white;font-weight:bold;':''">到期时间:{{ExpireTime}}</span>
			<span v-else>开通会员享受更多权益</span>
		</view>
		<view class="contain">
			<!-- <p>选择会员方案</p> -->
			<u-subsection :list="subsection" :current="curNow" @change="sectionChange" fontSize='30rpx'
				activeColor="#4F46E5" inactiveColor="#666666" bgColor="rgba(79, 70, 229, 0.05)"
				style="height: 80rpx;"></u-subsection>
			<view v-if="curNow == 0" class="itembox">
				<view class="item" :class="{ 'selected': selected === index }" @click="selectItem(index)"
					v-for="(item, index) in items" :key="item.id">
					<view class="item-content">
						<view class="item-title">{{ item.name }}</view>
						<view class="item-price">¥{{ item.price }}</view>
						<view class="item-desc">{{ item.content }}</view>
					</view>
				</view>
			</view>
			<view v-if="curNow == 1" class="itembox">
				<view class="item" :class="{ 'selected': selected === index }" @click="selectItem(index)"
					v-for="(item, index) in Fuelbagitems" :key="item.id">
					<view class="item-content">
						<view class="item-title">{{ item.num }}次</view>
						<view class="item-price">¥{{ item.money }}</view>
						<view class="item-desc">{{item.useGroup == 1?'个人':item.useGroup == 2?'企业':''}}可用</view>
						<view class="item-desc">{{ item.num }}次电话联系次数</view>
					</view>
				</view>
			</view>
			<p>优惠方案</p>
			<view class="itembox">
				<view class="item item3" @click="hasyhq?showyhq = true:''">
					<view style="display: flex;"><u-icon name="coupon-fill" color="#4F46E5" size="30"
							label="选择优惠券"></u-icon></view>
					<view style="display: flex;">
						<span v-if="insteadPrice !=0 &&hasyhq"
							style="color: #fa3534;margin-right: 20rpx;">-{{insteadPrice}}¥</span>
						<span v-if="discountPrice !=0 &&hasyhq"
							style="color: #fa3534;margin-right: 20rpx;">{{discountPrice/10}}折</span>
						<span v-if="!hasyhq" style="color: #666666;margin-right: 20rpx;">无可用优惠券</span>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
			</view>
			<p>支付方式</p>
			<view class="itembox">
				<view class="item item2" :class="{ 'selected': payselected === 0 }" @click="selectpayItem(0)">
					<view style="display: flex;"><u-icon name="weixin-fill" color="#53c21d" size="30"
							label="微信支付"></u-icon></view>
				</view>
				<!-- <view class="item item2" :class="{ 'selected': payselected === 1 }" @click="selectpayItem(1)">
					<view style="display: flex;"><u-icon name="zhifubao" color="#3c9cff" size="30" label="支付宝"></u-icon>
					</view>
				</view> -->
			</view>
			<view class="tips">
				<span>会员权益：</span>
				<span>1.享受平台所有高级功能</span>
				<span>2.专属客服一对一服务</span>
				<span>3.会员专属标识</span>
			</view>
		</view>
		<view style="height: 21vh;width: 100%;"></view>
		<view class="bottom">
			<view class="amount"><span>支付金额</span>
				<p>¥{{orderFeechange}}</p>
			</view>
			<view style="margin-top: 30rpx; margin-bottom: 40rpx;"><u-button type="primary" text="立即开通"
					@click="handlePayment"></u-button></view>
		</view>

		<u-popup :show="showyhq" @close="closeyhq" round='20' @touchmove.stop.prevent>
			<view class="yhqpopup">
				<text>选择优惠券</text>
			</view>
			<u-divider></u-divider>
			<view style="max-height: 700rpx; overflow: auto;">
				<view class="yhqitem" v-for="(item,index) in CouponList" :key="item.id"
					:class="item.status==1?'bg-1':'bg-2'">
					<view class="item-top">
						<view>
							<span v-if="item.deductionType == 1" :class="item.status==1?'':'font-color'"
								style="color:#4F46E5;font-size: 50rpx; font-weight: bold; margin-right: 20rpx;">¥{{item.insteadPrice}}</span>
							<span v-if="item.deductionType == 2" :class="item.status==1?'':'font-color'"
								style="color:#4F46E5;font-size: 50rpx; font-weight: bold; margin-right: 20rpx;">{{item.insteadPrice/10}}折券</span>
							<span class="containtext" :class="item.status==1?'':'font-color'">{{item.content}}</span>
						</view>
						<view>
							<u-button color="#4F46E5" plain customStyle='width:120rpx;height:55rpx' text="使用"
								:disabled="item.status==1?false:true"
								@click="selectCoupon(item.id,item.insteadPrice,item.deductionType)"></u-button>
						</view>
					</view>
					<view class="item-bottom containtext" :class="item.status==1?'':'font-color'">
						有效期至 {{item.expireTime}}
					</view>
				</view>
			</view>

		</u-popup>

		<!-- <u-popup :show="showGetyhq" @close="closeGetyhq" mode="center" round='20' closeable
			customStyle="width:80%;overflow: hidden;">
			<view class="getyhq">
				<span style="font-size: 60rpx;color: #fa3534;font-weight:900;">¥<text
						style="font-size: 120rpx;">{{couponinfo.insteadPrice}}</text></span>
				<p style="font-size: 32rpx;">{{couponinfo.name}}</p>
				<p style="font-size: 32rpx;">
					{{couponinfo.businessType == 1?'vip充值可用':couponinfo.businessType == 2?'增量包充值可用':'全场通用优惠券'}}</p>
				<p style="font-size: 28rpx;color: #666666;">每人限领1张</p>
				<p style="font-size: 28rpx;color: #999999;">有效期：至{{couponinfo.expireTime}}</p>
				<view style="width: 70%;">
					<u-button color="#fa3534" shape="circle" size="large" text="立即领取" @click="getyhq"></u-button>
				</view>
			</view>
		</u-popup> -->
		<CouponPopup :showGetyhq="showGetyhq" couponId="131932161" :businessId="businessId"
			@update:showGetyhq="updateShowGetyhq" @onReceiveSuccess='getCouponlist()'></CouponPopup>
		<u-overlay :show="showuploadImage">
			<view class="autloading"
				style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;">
				<u-loading-icon :show="showuploadImage" color="white"></u-loading-icon>
			</view>

		</u-overlay>
	</view>
</template>

<script>
	import Index from "@/common/index-model.js"
	let index = new Index();
	let that = null;
	export default {
		data() {
			return {
				quantity: '',
				businessId: '',
				couponinfo: '',
				subsection: ['会员充值', '加油包充值'],
				curNow: 0,
				showGetyhq: false,
				showyhq: false,
				hasyhq: false,
				userid: '',
				entid: '',
				payselected: 0,
				selected: 0,
				items: [],
				Fuelbagitems: [],
				CouponList: [],
				couponUseId: 0,
				insteadPrice: 0,
				discountPrice: 0,
				perOrEnt: '',
				ExpireTime: '',
				isvip: '',
				showuploadImage: false,
				amountOfMoney: 0,
				buttonlock: false,
				userinfo: ''
			}
		},
		onLoad(opt) {
			this.gethomepage()
			this.userid = opt.userId
			this.entid = opt.entid
			if (opt.code && opt.code == 503) this.curNow = 1
			if (opt.code && opt.code == 504) this.curNow = 0
			console.log("uid", this.userid, opt.entid)
			// this.getCouponinfo()
			this.isactAvailable()
			this.getViplist()
			this.getFuelbaglist()
			this.getCouponlist()
		},
		onShow() {
			this.gethomepage()
			this.getCouponlist()
			this.isactAvailable()
		},
		computed: {
			orderFeechange() {
				if (this.items[this.selected]) {
					let price = 0;
					// 获取基础价格
					if (this.curNow === 0) {
						price = this.items[this.selected].price;
					} else if (this.curNow === 1 && this.Fuelbagitems[this.selected]) {
						price = this.Fuelbagitems[this.selected].money;
					}

					// 处理输入值为空或非数字
					const insteadPrice = Number(this.insteadPrice) || 0;
					const discountPrice = Number(this.discountPrice) || 0;
					console.log("计算", insteadPrice, discountPrice)
					// 计算金额并修复浮点精度
					let amount = price
					if (insteadPrice != 0) {
						amount = price - insteadPrice;
					}
					if (discountPrice != 0) {
						amount = price * discountPrice * 0.01
					}
					amount = parseFloat(amount.toFixed(2)); // 关键修复：强制保留两位小数

					// 处理负数
					this.amountOfMoney = Math.max(0, amount);
					return this.amountOfMoney;
				}
				return 0; // 默认返回0
			}
		},
		methods: {
			gethomepage() {
				index.getPublicUserMember({}, '/client/individual/homePage', 'get', res => {
					if (res.data.code == 200 && res.data.success) {
						this.userinfo = res.data.result;
						console.log("充值userinfo", this.userinfo)
						if (this.userinfo.enIdentity == 0) {
							this.perOrEnt = 'per'
							this.ExpireTime = this.userinfo.vipExpireTime
							this.isvip = this.userinfo.vip
							this.quantity = this.userinfo.userTeleIncrementalNum
						} else {
							this.perOrEnt = 'ent'
							this.ExpireTime = this.userinfo.enterpriseVipExpireTime
							this.isvip = this.userinfo.enterpriseVip
							this.quantity = this.userinfo.entTelIncrementalNum
						}
					} else {
						index.show_tips(res.data.message);
						return false
					}
				})
			},
			//参与活动资格
			isactAvailable() {
				index.getPublicUserMember({}, `/apclient/appActivity/actAvailable/131932161`, 'get', res => {
					if (res.data.code === 200 && res.data.success) {
						this.businessId = res.data.result.businessId
						this.showGetyhq = true
					} else {
						return false
					}
				});
			},
			updateShowGetyhq(value) {
				this.showGetyhq = value;
			},
			sectionChange(index) {
				this.curNow = index
				console.log("选择", this.curNow)
				this.couponUseId = 0
				this.insteadPrice = 0
				this.discountPrice = 0
				this.selected = 0
			},
			selectCoupon(id, insteadPrice, deductionType) {
				this.couponUseId = id
				if (deductionType == 1) {
					this.insteadPrice = insteadPrice
					this.discountPrice = 0
				}
				if (deductionType == 2) {
					this.insteadPrice = 0
					this.discountPrice = insteadPrice
				}
				this.showyhq = false
			},
			closeyhq() {
				this.showyhq = false
			},
			closeGetyhq() {
				this.showGetyhq = false
			},
			// getyhq() {
			// 	if (this.buttonlock) {
			// 		return
			// 	}
			// 	this.buttonlock = true
			// 	console.log('领取优惠券')
			// 	index.getPublicUserMember({}, '/apclient/appCouponInfo/receive/' + this.couponinfo.id, 'post', res => {
			// 		if (res.data.code == 200 && res.data.success) {
			// 			console.log("领取成功", res.data)
			// 			index.show_tips("领取成功")
			// 			this.getCouponlist()
			// 			setTimeout(() => {
			// 				this.buttonlock = false
			// 				this.showGetyhq = false
			// 			}, 1000)
			// 		} else {
			// 			index.show_tips(res.data.message)
			// 			this.buttonlock = false
			// 			return false
			// 		}
			// 	})
			// },
			selectItem(index) {
				console.log(index)
				this.selected = index;
				this.couponUseId = 0
				this.insteadPrice = 0
				this.discountPrice = 0
			},
			selectpayItem(index) {
				this.payselected = index;
			},
			getViplist() {
				let useGroup = ''
				if (this.entid == 0) {
					useGroup = 1
				} else {
					useGroup = 2
				}
				index.getPublicUserMember({}, '/apclient/appVipInfo/availableVipList/' + useGroup, 'get', res => {
					console.log('vip信息', res.data.result)
					this.items = res.data.result
				})
			},
			getFuelbaglist() {
				let useGroup = ''
				if (this.entid == 0) {
					useGroup = 1
				} else {
					useGroup = 2
				}
				index.getPublicUserMember({}, '/apclient/appIncrementalPackage/avaliableList/1/' + useGroup, 'get',
					res => {
						console.log('加油包', res.data.result)
						this.Fuelbagitems = res.data.result
					})
			},
			getCouponlist() {
				index.getPublicUserMember({
					"status": 1
				}, '/apclient/appCouponInfo/getMyCouponList', 'get', res => {
					console.log('优惠券', res)
					this.CouponList = res.data.result
					if (!this.CouponList || this.CouponList.length < 1) {
						this.hasyhq = false
					} else {
						this.hasyhq = true
					}
				})
			},
			// getCouponinfo() {
			// 	index.getPublicUserMember({}, '/apclient/appCouponInfo/detail/1930931389119426562', 'get', res => {
			// 		if (res.data.code == 200 && res.data.success) {
			// 			this.couponinfo = res.data.result
			// 			if (res.data.result.status == 1) {
			// 				this.showGetyhq = true
			// 			}
			// 			console.log(res.data)
			// 		} else {
			// 			index.show_tips(res.data.message)
			// 			return false
			// 		}
			// 	})
			// },
			// 添加支付方法
			async handlePayment() {
				this.showuploadImage = true
				let sends = {}
				if (this.curNow == 0) {
					console.log("items", this.items)
					sends = {
						"bussinessType": 1,
						"bussinessId": this.items[this.selected].id,
						"couponUse": this.couponUseId == 0 ? 0 : 1,
						"couponUseId": this.couponUseId == 0 ? '' : this.couponUseId,
						"orderFee": this.amountOfMoney,
						"totalFee": this.items[this.selected].price,
						"userId": this.userid
					}
				} else if (this.curNow == 1) {
					console.log("Fuelbagitems", this.Fuelbagitems)
					sends = {
						"bussinessType": 2,
						"bussinessId": this.Fuelbagitems[this.selected].id,
						"couponUse": this.couponUseId == 0 ? 0 : 1,
						"couponUseId": this.couponUseId == 0 ? '' : this.couponUseId,
						"orderFee": this.amountOfMoney,
						"totalFee": this.Fuelbagitems[this.selected].money,
						"userId": this.userid
					}
				}

				console.log(sends)
				if (this.payselected == 1) {
					// console.log("支付宝")
					// uni.getProvider({
					// 	service: 'payment',
					// 	success: (res) => {
					// 		if (res.provider.includes('alipay')) {
					// 			index.getPublicUserMember(sends, '/aliPay/appPay', 'post', res => {
					// 				if (res.data.code == 200 && res.data.success) {
					// 					this.showuploadImage = false
					// 					console.log("支付", res)
					// 					if (res.data.result == '支付成功') {
					// 						index.show_tips("开通成功")
					// 						setTimeout(() => {
					// 							index.navigate_back()
					// 						}, 1000)
					// 						return
					// 					}
					// 					// 3. 调起支付宝支付
					// 					uni.requestPayment({
					// 						provider: 'alipay',
					// 						orderInfo: res.data.result
					// 						.orderInfo, // 后端返回的订单字符串
					// 						success: (payRes) => {
					// 							console.log('支付成功', payRes)
					// 							uni.navigateTo({
					// 								url: "/pagesB/rechargeVip/chargeResult?type=1&&orderId=" +
					// 									res.data.result.orderId
					// 							});
					// 						},
					// 						fail: (err) => {
					// 							console.error('支付失败', err)
					// 							uni.navigateTo({
					// 								url: "/pagesB/rechargeVip/chargeResult?type=0&&orderId=" +
					// 									res.data.result
					// 									.orderId +
					// 									"&&sends=" + JSON
					// 									.stringify(sends)
					// 							});
					// 						}
					// 					});
					// 				} else {
					// 					this.showuploadImage = false
					// 					index.show_tips(res.data.message)
					// 					return false
					// 				}
					// 			})


					// 		}
					// 	}
					// })
				}
				if (this.payselected == 0) {
					console.log("微信支付")
					index.getPublicUserMember(sends, '/wxPay/miniAppPay', 'post', res => {
						if (res.data.code == 200 && res.data.success) {
							this.showuploadImage = false
							console.log("支付", res.data.result)
							if (res.data.result == '支付成功') {
								index.show_tips("开通成功")
								setTimeout(() => {
									index.navigate_back()
								}, 1000)
								return
							}
							uni.requestPayment({
								provider: 'wxpay', // 支付提供商
								timeStamp: JSON.parse(res.data.result.orderInfo).timeStamp, // 时间戳
								nonceStr: JSON.parse(res.data.result.orderInfo).nonceStr, // 随机字符串
								package: JSON.parse(res.data.result.orderInfo).package, // 统一下单接口返回的prepay_id参数值
								signType: JSON.parse(res.data.result.orderInfo).signType, // 签名算法
								paySign: JSON.parse(res.data.result.orderInfo).paySign, // 签名
								success: (payRes) => {
									console.log('支付成功', payRes)
									uni.navigateTo({
										url: "/pagesB/rechargeVip/chargeResult?type=1&&orderId=" +
											res.data.result.orderId
									});
								},
								fail: (err) => {
									console.error('支付失败', err)
									uni.navigateTo({
										url: "/pagesB/rechargeVip/chargeResult?type=0&&orderId=" +
											res.data.result
											.orderId +
											"&&sends=" + JSON
											.stringify(sends)
									});
								}
							});
						} else {
							this.showuploadImage = false
							index.show_tips(res.data.message)
							return false
						}
					})
				}
			},

		}
	}
</script>

<style lang="scss">
	.top {
		width: 90%;
		margin: 30rpx auto;
		background-color: rgba(79, 70, 229, 0.05);
		box-sizing: border-box;
		padding: 40rpx;
		border-radius: 20rpx;

		span {
			font-size: 28rpx;
			color: #6B7280;
		}

		p {
			font-size: 40rpx;
			padding: 10rpx 0;
		}
	}

	.contain {
		width: 90%;
		margin: 0 auto;
		font-size: 30rpx;

		.itembox {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			margin-top: 30rpx;

			.item {
				box-sizing: border-box;
				width: 48%;
				margin-bottom: 30rpx;
				position: relative;
				border-radius: 20rpx;
				overflow: hidden;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #fff;
				transition: all 0.3s ease;
				border: 1px solid #E5E7EB;
			}
		}
	}

	.item2 {
		width: 100% !important;
		padding: 40rpx;
		font-size: 30rpx;
		justify-content: space-between !important;
	}

	.item3 {
		width: 100% !important;
		padding: 20rpx 40rpx;
		font-size: 30rpx;
		justify-content: space-between !important;
	}

	.item-title {
		font-size: 36rpx;
		font-weight: 500;
		color: #000000;
		margin-bottom: 10px;
	}

	.item-price {
		font-size: 40rpx;
		font-weight: 600;
		color: #000000;
		margin-bottom: 10px;
	}

	.item-desc {
		font-size: 24rpx;
		color: #6B7280;
	}

	.item-content {
		width: 100%;
		text-align: center;
		padding: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	/* 选中状态 */
	.selected {
		border: 1px solid #4F46E5 !important;
		background-color: rgba(79, 70, 229, 0.05) !important;
	}

	.selected .item-title {
		color: #4F46E5;
	}

	.tips {
		display: flex;
		flex-direction: column;
		font-size: 24rpx;
		color: #6B7280;
	}

	.bottom {
		width: 100%;
		// height: 20vh;
		position: fixed;
		padding: 40rpx;
		box-sizing: border-box;
		bottom: 0;
		border-top: 1px solid #f3f4f6;
		background-color: #fff;
	}

	.amount {
		display: flex;
		justify-content: space-between;

		span {
			font-size: 28rpx;
			color: #6B7280;
		}

		p {
			font-size: 36rpx;
			color: #4F46E5;
		}
	}

	.yhqpopup {
		padding: 30rpx;
		padding-bottom: 0;
		font-size: 35rpx;
		font-weight: 500;
	}

	.yhqitem {
		// height: 180rpx;
		width: 90%;
		margin: 10rpx auto;
		margin-bottom: 30rpx;
		border-radius: 20rpx;
		padding: 25rpx 30rpx;
		box-sizing: border-box;

		.item-top {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}

	.containtext {
		color: #6B7280;
		font-size: 28rpx;
	}

	.bg-1 {
		background: linear-gradient(0deg, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)), linear-gradient(90deg, rgba(79, 70, 229, 0.1) 0%, rgba(79, 70, 229, 0.05) 100%);
	}

	.bg-2 {
		background: linear-gradient(0deg, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)), linear-gradient(90deg, #F3F4F6 0%, #F9FAFB 100%);
	}

	.font-color {
		color: #9ca3af !important;
	}

	.getyhq {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx 0;

		p {
			padding: 8rpx 0;
		}
	}

	// .selected-tag {
	// 	position: absolute;
	// 	top: 0;
	// 	right: 0;
	// 	background-color: #ff6b6b;
	// 	color: white;
	// 	font-size: 12px;
	// 	padding: 3px 8px;
	// 	border-bottom-left-radius: 10px;
	// 	z-index: 12;
	// }
</style>